<template>
  <div class="crete-code">
    <breadcrumb class="breadcrumb-container"></breadcrumb>
    <el-row>
      <el-col :xl="7" :lg="7" :xs="24" :md="24" :sm="24" class="mr20">
        <el-button icon="el-icon-plus" type="primary" size="small" @click="qCAddShow">新增二维码</el-button>
        <el-table size="small" highlight-current-row :data="batch_data" v-loading="batch_loading" @row-click="handleCodeList" :header-cell-style="{background:'#f2f2f2'}" class="mt20">
          <el-table-column align="center" label="批次号" prop="batch_num" width="70"></el-table-column>
          <el-table-column align="center" label="数量" prop="quantity"></el-table-column>
          <el-table-column align="center" label="生成时间" prop="create_at"></el-table-column>
          <el-table-column align="center" label="操作">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="handleDownloadAll(scope.row.agent_num, scope.row.batch_num)">全部导出</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination :total="batch_page.total" :current-page.sync="batch_page.current" layout="total, prev, pager, next, jumper"  class="fr mt20" @current-change="handleCurrentChange" :page-size="batch_page.pageSize"></el-pagination>
      </el-col>
      <el-col :xl="15" :lg="16" :xs="24" :md="24" :sm="24">
        <el-form class="mb20" :model="searchForm" label-width="80px" size="small" inline>
          <el-form-item label="展业码编号">
            <el-input placeholder="输入展业码编号" v-model="searchForm.code"></el-input>
          </el-form-item>
          <el-form-item label="商户编号">
            <el-input placeholder="输入商户编号" v-model="searchForm.merchant_num"></el-input>
          </el-form-item>
          <el-form-item label="商户名称">
            <el-input placeholder="输入商户名称" v-model="searchForm.mch_name"></el-input>
          </el-form-item>
          <!-- <el-form-item label="生成时间">
            <el-date-picker type="daterange" start-placeholder="开始时间" end-placeholder="结束时间" value-format="yyyy-MM-dd" v-model="searchForm.time" @change="handleStartTime"></el-date-picker>
          </el-form-item> -->
          <el-form-item>
            <el-button icon="el-icon-search" type="success" size="small" @click="handleBatchSearch">查询</el-button>
            <el-button icon="el-icon-search" style="margin-top:0px" type="info" size="small" @click="qrcodeExprot">批量导出</el-button>
          </el-form-item>
        </el-form>
        <el-table size="small" ref="multipleTable" :data="code_data" v-loading="loading" @selection-change="onSelectedChange" :header-cell-style="{background:'#f2f2f2'}">
          <el-table-column type="selection" label="全选" width="40"></el-table-column>
          <el-table-column align="center" label="展业码编号" prop="code"></el-table-column>
          <el-table-column align="center" label="商户编号" prop="mch_num"></el-table-column>
          <el-table-column align="center" label="所属代理商" prop="agent_name"></el-table-column>
          <el-table-column align="center" label="所属门店" prop="store_name"></el-table-column>
          <el-table-column align="center" label="绑定时间">
            <template slot-scope="scope">
                <span>{{ scope.row.bind_at === 0 ? '无' : scope.row.bind_at }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="绑定状态">
            <template slot-scope="scope">
              <span :class="scope.row.is_binded === '未绑定' ? 'err' : ''">{{ scope.row.is_binded }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="Down(scope.row.code)">导出</el-button>
              <el-button v-if="scope.row.is_binded === '已绑定'" type="text" size="small" @click="unBindCode(scope.row.code, scope.$index)">解绑</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination :total="page.total" :current-page.sync="page.current" layout="total, prev, pager, next, jumper"  class="fr mt20" @current-change="handleCurrentChangeList" :page-size="page.pageSize"></el-pagination>
      </el-col>
    </el-row>
    <el-dialog title="新增二维码" width="800px" :visible.sync="qcShow">
      <dialog-code ref="code" @show="handleDialogOff" :name="'蚂蚁嗨客测试'" :code="'https://mat.uphicoo.com/22b2e80e-9a82-11e8-aa35-10bf48e1a920.jpg'"></dialog-code>
      <div slot="footer"  class="dialog-footer">
        <el-button @click="qcShow = false">取消</el-button>
        <el-button type="primary" @click="qrCodeAdd">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Breadcrumb from '@/components/Breadcrumb'
import { getBatchList, getBatchListPage, getCodeList, searchCodeList, downloadFileAll, exprotQrcode, exprotQrcodeOne, postUnbindCode, getCodeListCurrent } from '@/api/myAngent'
import { mapGetters } from 'vuex'
import DialogCode from './components/shopCode/code'
import { img_2_zip } from '@/vendor/Img2Zip'

export default {
  components: {
    Breadcrumb,
    DialogCode
  },
  data() {
    return {
      loading: false,
      batch_loading: false,
      qcShow: false,
      qrcode_item: {
        quantity: 0,
        style: 1,
        logo: []
      },
      multipleSelection: [],
      batch_data: [],
      code_data: [],
      batch_page: {
        total: 0,
        pageSize: 0,
        current: 1
      },
      page: {
        total: 0,
        pageSize: 0,
        current: 1
      },
      searchForm: {
        merchant_num: '',
        agent_num: '',
        mch_name: '',
        code: '',
        batch_num: '',
        time: []
      },
      listTable: {
        agent_num: '',
        batch_num: ''
      },
      stroes: []
    }
  },
  methods: {
    Down(code) {
      exprotQrcodeOne(code).then(res => {
        if (res.data.errorCode === 0) {
          this.downloadFile(new Date().getTime(), res.data.result)
        } else {
          this.$message.error(res.data.errorMsg)
        }
      })
    },
    handleCodeList(row) {
      this.listTable.agent_num = row.agent_num
      this.listTable.batch_num = row.batch_num
      this.loading = true
      getCodeList(row).then(res => {
        if (res.data.errorCode === 0) {
          this.code_data = res.data.result.data
          this.page.total = res.data.result.total
          this.page.current = res.data.result.current_page
          this.page.pageSize = res.data.result.per_page
          this.loading = false
        } else {
          this.loading = false
          this.$message.error(res.data.errorMsg)
        }
      })
    },
    handleStartTime(v) {
      this.searchForm.start = v
    },
    qCAddShow() {
      this.qcShow = true
    },
    handleCurrentChangeList(v) {
      this.loading = true
      getCodeListCurrent(this.listTable, v).then(res => {
        if (res.data.errorCode === 0) {
          this.code_data = res.data.result.data
          this.page.total = res.data.result.total
          this.page.current = res.data.result.current_page
          this.page.pageSize = res.data.result.per_page
          this.loading = false
        } else {
          this.loading = false
          this.$message.error(res.data.errorMsg)
        }
      })
    },
    handleCurrentChange(v) {
      this.batch_loading = true
      getBatchListPage(v).then(response => {
        this.batch_data = response.data.result.data
        this.batch_page.total = response.data.result.total
        this.batch_page.current = response.data.result.current_page
        this.batch_page.pageSize = response.data.result.per_page
        this.batch_loading = false
      })
    },
    batchList() {
      getBatchList().then(res => {
        if (res.data.errorCode === 0) {
          this.batch_loading = true
          this.batch_data = res.data.result.data
          this.batch_page.total = res.data.result.total
          this.batch_page.current = res.data.result.current_page
          this.batch_page.pageSize = res.data.result.per_page
          this.batch_loading = false
        } else {
          this.$message.error(res.data.errorMsg)
        }
      })
    },
    qrCodeAdd() {
      this.$refs.code.imgDown()
    },
    onSelectedChange(v) {
      this.multipleSelection = v
    },
    qrcodeExprot() {
      exprotQrcode(this.multipleSelection).then(res => {
        if (res.data.errorCode === 0) {
          img_2_zip(res.data.result)
        } else {
          this.$message.error(res.data.errorMsg)
        }
      })
    },
    unBindCode(code, index) {
      postUnbindCode(code).then(res => {
        if (res.data.errorCode === 0) {
          this.$message.success('操作成功')
          this.code_data[index].is_binded = '未绑定'
        } else {
          this.$message.error(res.data.errorMsg)
        }
      })
    },
    handleDialogOff() {
      this.qcShow = false
      this.batchList()
    },
    base64ToBlob(code) {
      const parts = code.split(';base64,')
      const contentType = parts[0].split(':')[1]
      const raw = window.atob(parts[1])
      const rawLength = raw.length
      const uInt8Array = new Uint8Array(rawLength)
      for (let i = 0; i < rawLength; ++i) {
        uInt8Array[i] = raw.charCodeAt(i)
      }
      return new Blob([uInt8Array], { type: contentType })
    },
    downloadFile(fileName, content) {
      const aLink = document.createElement('a')
      const blob = this.base64ToBlob(content) // new Blob([content]);
      const evt = document.createEvent('HTMLEvents')
      evt.initEvent('click', true, true) // initEvent 不加后两个参数在FF下会报错  事件类型，是否冒泡，是否阻止浏览器的默认行为
      aLink.download = fileName
      aLink.href = URL.createObjectURL(blob)
      aLink.click()
    },
    handleDownloadAll(agent_num, batch_num) {
      const loading = this.$loading({
        lock: true,
        text: '正在生成中，请稍候...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      downloadFileAll(agent_num, batch_num).then(res => {
        if (res.data.errorCode === 0) {
          img_2_zip(res.data.result).then(res => {
            loading.close()
          }).catch(() => {
            loading.close()
            this.$message.error('生成失败，请重试...')
          })
        } else {
          loading.close()
          this.$message.error(res.data.errorMsg)
        }
      })
    },
    handleBatchSearch() {
      this.loading = true
      searchCodeList(this.searchForm, this.listTable).then(res => {
        if (res.data.errorCode === 0) {
          this.code_data = res.data.result.data
          this.page.total = res.data.result.total
          this.page.current = res.data.result.current_page
          this.page.pageSize = res.data.result.per_page
          this.loading = false
        } else {
          this.loading = false
          this.$message.error(res.data.errorMsg)
        }
      })
    }
  },
  computed: {
    ...mapGetters([
      'id'
    ])
  },
  created() {
    this.batchList()
  }
}
</script>

<style lang="scss" scpoed>
.qr_code{
  .el-dialog__body{
    .el-row{
      span{
        font-size: 12px;
      }
      margin-bottom: 10px;
      .el-radio+.el-radio{
        margin-left: 5px;
      }
      .el-checkbox-group{
        display: inline-block;
        vertical-align: top;
        margin: 0;
        padding: 0;
        label{
          display: block;
          margin-left: 0;
        }
      }
    }
    .box-body{
      &>div{
        display: inline-block;
        vertical-align: top;
        p{
          margin: 0;
        }
        &:last-child{
          margin-left: 30px;
        }
      }
    }
  }
}
  
</style>
